/**
 * website
 * com.inmaytide.website.utils
 * CommonUtils.java
 * May 20, 2016 9:48:11 AM
 */
package com.inmaytide.website.utils;

import com.inmaytide.website.domain.entities.system.SysUser;
import com.inmaytide.website.utils.configurations.SystemConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.util.ObjectUtils;

/**
 * @author luomiao
 * @since May 20, 2016
 */
public class CommonUtils {

    public static SysUser getCurrentUser() {
        return getSessionAttribute(SystemConstants.SESSION_CURRENTUSER_KEY);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getSessionAttribute(String key) {
        Object value = getCurrentSession().getAttribute(key);
        return ObjectUtils.isEmpty((T) value) ? null : (T) value;
    }

    public static Session getCurrentSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static void setSessionAttribute(String key, Object value) {
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute(key, value);
    }

    public static String findLoginMessage(AuthenticationException e) {
        if (StringUtils.startsWithIgnoreCase(e.getMessage(), "UnknownAccount")) {
            return SystemConstants.LOGIN_UNKNOWACCOUNT;
        } else if (StringUtils.startsWithIgnoreCase(e.getMessage(), "LockedAccount")) {
            return SystemConstants.LOGIN_ACCOUNTLOCKED;
        } else {
            return SystemConstants.LOGIN_NOTMATCH;
        }
    }

    public static boolean hasPermission(String permit) {
        return SecurityUtils.getSubject().isPermitted(permit);
    }

    public static boolean hasRole(String roleCode) {
        return SecurityUtils.getSubject().hasRole(roleCode);
    }

}
